<template>
  <!-- 应用容器 -->
  <div id="app">
    <!-- 电影添加组件 -->
    <MovieAdd @add-movie="addMovie" />
    <!-- 电影列表组件 -->
    <MovieList :movies="movies" @delete-movie="deleteMovie" @view-movie-details="viewMovieDetails" />
    <!-- 电影详情模态框 -->
    <MovieDetailsModal :show="showDetailsModal" :movie="selectedMovie" @edit-movie="editMovie"
      @close-details="closeMovieDetails" />
    <!-- 电影编辑模态框 -->
    <MovieEditModal :show="showEditModal" :movie="editedMovie" @save-movie="saveMovie" @cancel-edit="cancelEdit" />
  </div>
</template>
<script setup>
// 引入 Vue 3 的核心 API
import { ref, watch } from 'vue';
// 引入组件
import MovieList from './components/MovieList.vue';
import MovieAdd from './components/MovieAdd.vue';
import MovieDetailsModal from './components/MovieDetailsModal.vue';
import MovieEditModal from './components/MovieEditModal.vue';
// 响应式电影列表（带本地存储）
const movies = ref(JSON.parse(localStorage.getItem('movies')) || [
  {
    id: 1,
    title: '复仇者联盟4',
    year: 2019,
    director: '安东尼·罗素、乔·罗素',
    genre: '科幻、动作'
  },
  {
    id: 2,
    title: '泰坦尼克号',
    year: 1997,
    director: '詹姆斯·卡梅隆',
    genre: '爱情、灾难'
  },
  {
    id: 3,
    title: '阿凡达',
    year: 2009,
    director: '詹姆斯·卡梅隆',
    genre: '科幻、冒险'
  }
]);
// 响应式变量
const selectedMovie = ref(null); // 当前选中电影
const showDetailsModal = ref(false); // 详情模态框状态
const showEditModal = ref(false); // 编辑模态框状态
const editedMovie = ref(null); // 待编辑电影
// 监听电影列表变化并保存到本地存储
watch(movies, (newValue) => {
  localStorage.setItem('movies', JSON.stringify(newValue));
}, { deep: true });
// 添加电影方法
const addMovie = (movie) => {
  const newId = movies.value.length > 0 ? movies.value[movies.value.length - 1].id + 1
    : 1;
  movies.value.push({ id: newId, ...movie }); // 添加新电影
};
// 删除电影方法
const deleteMovie = (id) => {
  movies.value = movies.value.filter(movie => movie.id !== id); // 过滤删除
};
// 查看详情方法
const viewMovieDetails = (id) => {
  selectedMovie.value = movies.value.find(movie => movie.id === id); // 查找电影
  showDetailsModal.value = true; // 显示详情模态框
};
// 关闭模态框方法
const closeMovieDetails = () => {
  showDetailsModal.value = false;
  showEditModal.value = false;
};
// 编辑电影方法
const editMovie = (movie) => {
  showDetailsModal.value = false;
  showEditModal.value = true;
  editedMovie.value = { ...movie }; // 复制电影数据
};
// 保存编辑方法
const saveMovie = (movie) => {
  const index = movies.value.findIndex(m => m.id === movie.id);
  if (index !== -1) {
    movies.value.splice(index, 1, movie); // 更新电影列表
    selectedMovie.value = movie; // 更新选中电影
  }
  showEditModal.value = false;
  showDetailsModal.value = true;
};
// 取消编辑方法
const cancelEdit = () => {
  showEditModal.value = false;
  showDetailsModal.value = true;
};
</script>
<style>
#app {

  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin: 24px auto;
  max-width: 600px;
}
</style>